import { createRouter, createWebHashHistory } from 'vue-router'
import axios from 'axios'
import Login from '@/views/Login.vue'
import Index from '@/views/Index.vue'
import SecondPage from '@/views/SecondPage.vue'

const routes = [
  { path: '/login', component: Login },
  {
    path: '/',
    component: Index,
    children: [{ name: 'second', path: '/second', component: SecondPage }],
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')
  let isValid = null
  if (token) {
    isValid = await axios.get(
      'https://mock.apifox.com/m1/4019805-0-default/check_token',
      {
        params: {
          token,
        },
      }
    )

    if (isValid.data.status !== 200 && to.path !== '/login') {
      next({ path: '/login' })
    } else if (isValid.data.status === 200 && to.path === '/login') {
      next({ path: '/' })
    } else {
      next()
    }
  } else {
    if (to.path !== '/login') {
      next({ path: '/login' })
    } else {
      next()
    }
  }
})

export default router
